package com.dayu.tcp.service.client;

import com.dayu.tcp.logging.Log;
import com.dayu.tcp.logging.LogFactory;
import com.dayu.tcp.protocol.K1HeartbeatMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @author yehangtech
 * @date 2025/4/13 14:17
 * @description 用来处理客户端的心跳
 */
@ChannelHandler.Sharable
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {

    private static final Log log = LogFactory.getLog(ClientHeartbeatHandler.class);

    public ClientHeartbeatHandler() {
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.WRITER_IDLE) {
                Channel channel = ctx.channel();
                if (null != channel) {
                    if (log.isDebugEnabled()) {
                        log.debug("WRITER_IDLE, send heartbeat...");
                    }
                    channel.writeAndFlush(K1HeartbeatMsg.getInstance());
                }
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}
